MediaType
MIME Media-type parsing for Rust
Parsing
MediaType::parse
runs a zero-copy parsing: A MediaType
borrows the input string instead of copying it.
If you need an owned type, use MediaTypeBuf
.
use ;
let madia_type = "image/svg+xml; charset=UTF-8";
let svg = parse.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Construction
MediaType
is const-constructible. It can be defined as a constant.
Predefind names and values are defined in names
and values
modules.
use ;
const TEXT_PLAIN: MediaType = new;
const IMAGE_SVG: MediaType =
from_parts;
const TEXT_MARKDOWN: MediaType =
media_type!;
Parameters
Case Sensitivity
Comparisons are case-insensitive except parameter values.
let text_plain_lower = parse.unwrap;
let text_plain_upper = parse.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
Duplicate Parameter Names
The parser does not report duplicate parameter names as an error, but MediaType
recognizes only the last value.
let text_plain = parse.unwrap;
assert_eq!;
// Return the last charset value.
assert_eq!;
// Compare the last charset value.
assert_eq!;
Owned Type
MediaTypeBuf
is an owned version of MediaType
.
It is immutable but optimized for minimal stack and heap usage.
use ;
let text_plain: MediaTypeBuf = "text/plain; charset=UTF-8".parse.unwrap;
assert_eq!;
// Convert to MediaType
let mut text_markdown: MediaType = text_plain.to_ref;
text_markdown.subty = MARKDOWN;
assert_eq!;
MediaTypeList
MediaTypeList
parses a comma-separated list of MediaType
s used in the HTTP Accept
header. (RFC 7231)
use ;
let mut list = new;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Serialize and Deserialize
To enable serialization and deserialization, specify serde
feature in Cargo.toml
.
= { = "...", = ["serde"] }
let json = r#"
[
"text/plain",
"image/svg+xml; charset=UTF-8"
]
"#;
let decoded: = from_str.unwrap;